export interface SendCmdMessage<T = any> {
    sender: "plugin";
    receiver: "platform";
    type: "SendCmd";
    moduleName: string;
    cmdName: string;
    cmdParams: T;
}

export interface EventFnMessage<T = any> {
    sender: "platform";
    receiver: "plugin";
    type: "EventFn";
    moduleName: string;
    DataName: string;
    Data: T;
}

class PlatformBroadcast {
    private channel: BroadcastChannel;
    private receiveListeners: Set<(msg: SendCmdMessage) => void> = new Set();
    private sendListeners: Set<(msg: EventFnMessage) => void> = new Set();

    private static readonly CHANNEL_NAME = "Msg-Channel";
    constructor() {
        this.channel = new BroadcastChannel(PlatformBroadcast.CHANNEL_NAME);
        this.channel.onmessage = (e) => {
            if (!e.data?.type) return; // 忽略无效消息
            if (e.data.type === "SendCmd") {
                this.receiveListeners.forEach((listener) => listener(e.data));
            } else if (e.data.type === "EventFn") {
                this.sendListeners.forEach((listener) => listener(e.data));
            }
        };
    }

    // postMessage(msg: EventFnMessage) {
    //     this.channel.postMessage(msg);
    // }

    // onMessage(callback: (msg: SendCmdMessage) => void) {
    //     this.channel.onmessage = (e) => callback(e.data);
    // }

    onSend(callback: (msg: EventFnMessage) => void) {
        this.sendListeners.add(callback);
    }

    onReceive(callback: (msg: SendCmdMessage) => void) {
        this.receiveListeners.add(callback);
    }

    postMessage(msg: EventFnMessage) {
        this.channel.postMessage(msg);
    }

    offSend(callback: (msg: EventFnMessage) => void) {
        this.sendListeners.delete(callback);
    }

    offReceive(callback: (msg: SendCmdMessage) => void) {
        this.receiveListeners.delete(callback);
    }
}

export default new PlatformBroadcast();